package quantri.pqcn;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;

import utils.UtilsOnScopes;

import dbutil.ConnectDB;
import dbutil.DBUtils;

/*******************************************************************************
 * Filename : PhanQuyenChucNang.java Decription :Phân quyền sử dụng cho từng
 * User Created date : Jun 5, 2008 Author : Honglk
 ******************************************************************************/
public class PhanQuyenChucNang {
	private String nhom = "-1";
	private String idThanhVien = "-1";
	private String id ="";
	private String error;
	private List<Table> tables = null;

	public PhanQuyenChucNang() {
	}

	/***************************************************************************
	 * Method name : listUser Return type : List<User> Decription :Lâys ra danh
	 * sách tất cả các User Created date : Jun 5, 2008 Author : Honglk
	 **************************************************************************/
	public List<User> listUser() {
		List<User> li = new ArrayList<User>();
		String SQL = "SELECT DISTINCT name,id FROM thanhvien ";
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		if (array.size() > 0) {
			HashMap<String, Object> hash = new HashMap<String, Object>();
			for (int i = 0; i < array.size(); i++) {
				User user = new User();
				hash = (HashMap<String, Object>) array.get(i);
				user.setTenDangNhap(hash.get("name").toString());
				user.setId(hash.get("id").toString());
				li.add(user);
			}
		}
		return li;
	}

	
	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	/***************************************************************************
	 * Method name : listItemUser Return type : SelectItem[] Decription :Tạo các
	 * SELECTItem cho USER Created date : Jun 5, 2008 Author : Honglk
	 **************************************************************************/
	public SelectItem[] listItemUser() {
		List<User> li = this.listUser();
		SelectItem[] arrItem = new SelectItem[li.size() + 1];
		arrItem[0] = new SelectItem("-1", "Tất cả");
		for (int i = 0; i < li.size(); i++) {
			User user = li.get(i);
			arrItem[i + 1] = new SelectItem(user.getId(), user
					.getTenDangNhap());
		}
		return arrItem;
	}

	/***************************************************************************
	 * Method name : getListItemUser Return type : SelectItem[] Decription :Lấy
	 * ra các SELECTItem của USER Created date : Jun 5, 2008 Author : Honglk
	 **************************************************************************/
	public SelectItem[] getListItemUser() {
		return this.listItemUser();
	}

	/***************************************************************************
	 * Method name : listNhomChucNang Return type : List<NhomChucNang>
	 * Decription :Lấy ra tất cả các nhóm chức năng Created date : Jun 5, 2008
	 * Author : Honglk
	 **************************************************************************/
	public List<NhomChucNang> listNhomChucNang() {
		List<NhomChucNang> list = new ArrayList<NhomChucNang>();
		String SQL = "SELECT DISTINCT * FROM nhomchucnang";
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		if (array.size() > 0) {
			HashMap<String, Object> hash = new HashMap<String, Object>();
			for (int i = 0; i < array.size(); i++) {
				NhomChucNang group = new NhomChucNang();
				hash = (HashMap<String, Object>) array.get(i);
				group.setId(hash.get("id").toString());
				group.setName(hash.get("fullname").toString());
				list.add(group);
			}
		}
		return list;
	}

	/***************************************************************************
	 * Method name : listItemNhomChucNang Return type : SelectItem[] Decription
	 * :Tạo các SELECTItem cho NhomChucNang Created date : Jun 5, 2008 Author :
	 * Honglk
	 **************************************************************************/
	public SelectItem[] listItemNhomChucNang() {
		List<NhomChucNang> list = this.listNhomChucNang();
		int length = list.size() + 1;
		SelectItem[] arrItem = new SelectItem[length];
		arrItem[0] = new SelectItem("-1", "Tất cả");
		for (int i = 0; i < list.size(); i++) {
			NhomChucNang Gr = list.get(i);
			arrItem[i + 1] = new SelectItem(Gr.getId(), Gr.getName());
		}
		return arrItem;
	}

	/***************************************************************************
	 * Method name : getListItemNhomChucNang Return type : SelectItem[]
	 * Decription :Lấy ra các SELECTItem của NhomChucNang Created date : Jun 5,
	 * 2008 Author :Honglk
	 **************************************************************************/
	public SelectItem[] getListItemNhomChucNang() {
		return this.listItemNhomChucNang();
	}

	/***************************************************************************
	 * Method name : listTable Return type : String Decription :Để đưa dữ liệu
	 * ra table Created date : Jun 6, 2008 Author : Honglk
	 **************************************************************************/
	public String listTable() {
		this.setError("");
		List<Table> list = new ArrayList<Table>();
		String SQL = "SELECT DISTINCT A.gid,A.idthanhvien,C.name,B.fullname,A.id " +
				" FROM quyenchucnang A ,nhomchucnang B,thanhvien C"
				+ " WHERE A.gid = B.id AND C.id=A.idthanhvien AND "
				+ this.searchHelp(this.idThanhVien, this.nhom)
				+ "  ORDER BY name";
		System.out.println(SQL);
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		if (array.size() > 0) {
			HashMap<String, Object> hash = new HashMap<String, Object>();
			int stt = 0;
			for (int i = 0; i < array.size(); i++) {
				stt = i + 1;
				hash = (HashMap<String, Object>) array.get(i);
				Table table = new Table();
				table.setStt(String.valueOf(stt));
				table.setId(hash.get("id").toString());
				table.setUserName(hash.get("name").toString());
				table.setGroupName(hash.get("fullname").toString());
				table.setIdGroup((Integer) hash.get("gid"));
				table.setIdthanhvien((Integer) hash.get("idthanhvien"));
				list.add(table);
			}
		}
		this.setTables(list);
		return "okPQCN";
	}

	/***************************************************************************
	 * Method name : searchHelp Return type : String Decription :Hỗ trợ cho hàm
	 * search Created date : Jun 6, 2008 Author : Honglk
	 **************************************************************************/
	public String searchHelp(String idthanhvien, String groupId) {
		StringBuffer buffer = new StringBuffer();
		String strTemp = "";
//		String strTempCond1 = "uname LIKE '%" + userName + "%' OR '"
//				+ (userName.equals("-1") ? "0" : userName) + "'='0'";
		String strTempCond1 = "idthanhvien = '" + idthanhvien + "' OR '"
		+ (idthanhvien.equals("-1") ? "0" : idthanhvien) + "'= '0'";
		String strTempCond2 = "gid = '" + groupId + "' OR '"
				+ (groupId.equals("-1") ? "0" : groupId) + "'= '0'";

		strTemp = "(" + strTempCond1 + ") AND (" + strTempCond2 + ")";
		buffer.append("(");
		buffer.append(strTemp);
		buffer.append(")");
		return buffer.toString();
	}

	/***************************************************************************
	 * Method name : save Return type : String Decription :Luu xuong CSDL
	 * Created date : Jun 6, 2008 Author : Honglk
	 **************************************************************************/
	public String save() {
		ConnectDB.connectDB();
		
		this.setError("");
		String SQL1 = " SELECT COUNT(*) AS count FROM quyenchucnang "
				+ " WHERE idthanhvien='" + this.idThanhVien + "' AND gid='" + this.nhom
				+ "'";
		try {
			ArrayList<HashMap<String, Object>> array = ConnectDB
					.getDataTypeList(SQL1);
			HashMap<String, Object> hash = (HashMap<String, Object>) array
					.get(0);
			int count = Integer.parseInt(hash.get("count").toString());
			if(count > 0){
				this.setError("Chức năng và người dùng này đã tồn tại !");
				return "";
			}
			else if(this.idThanhVien.equals("-1")){
				this.setError("Bạn chưa chọn người dùng !");
				return "";
			}
			else if(this.nhom.equals("-1")){
				this.setError("Bạn chưa chọn Chức năng !");
				return "";
			}
			else if(this.id == null || this.id.equals(""))
			{
			 if (count == 0
					&& (!(this.nhom.equals("-1")) && !(this.idThanhVien
							.equals("-1")))) {
				PreparedStatement preStat = ConnectDB.connect
						.prepareStatement("INSERT INTO quyenchucnang(gid,idthanhvien) VALUES(?,?)");
//				preStat.setString(1, "");
				preStat.setInt(1, Integer.parseInt(this.nhom));
				preStat.setInt(2,Integer.parseInt(this.idThanhVien));
				preStat.executeUpdate();
				this.setError("Lưu thành công !");
			}
		 }
			else if(this.id != null && !(this.id.equals(""))){
				PreparedStatement preStat = ConnectDB.connect
				.prepareStatement("UPDATE quyenchucnang SET idthanhvien=?,gid=?"
						+ " WHERE id='" +this.id+"'");
				preStat.setInt(1,Integer.parseInt(this.idThanhVien));
				preStat.setInt(2, Integer.parseInt(this.nhom));
				preStat.executeUpdate();
				this.setError("Bạn đã cập nhật thành công !");
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.setError("Lưu không thành công !");
		}
		return "okPQCN";
	}

	/**************************************
	 * Method name		: delete
	 * Return type		: String
	 * Decription		:Xóa dòng dữ liệu
	 * Created date		: Jun 6, 2008
	 * Author			: Honglk
	 **************************************/
	public String delete() {
		try {
			// cach 1:
			// FacesContext fc = FacesContext.getCurrentInstance();
			// String id = (String) fc.getExternalContext()
			// .getRequestParameterMap().get("id");

			// cach2:
			HttpServletRequest request = UtilsOnScopes.getRequest();
			String id = request.getParameter("id");
			int count = DBUtils.deleteData("quyenchucnang", "id", id);
			if(count != 0){
				this.setError("Xóa thành công !");
			}
			else if(count == 0){
				this.setError("Xóa không thành công !");
				
			}
		} catch (Exception e) {
		}
		return "okPQCN";

	}
	
	public String edit(){
		HttpServletRequest req = UtilsOnScopes.getRequest();
		String idThanhvien = req.getParameter("maSothanhVien");
		String gid = req.getParameter("maSoChucNang");
		String id = req.getParameter("id");
		this.setError("");
		this.setIdThanhVien(idThanhvien);
		this.setNhom(gid);
		this.setId(id);
		return "okPQCN";
	}
	
	public String reset(){
		UtilsOnScopes.getSession().removeAttribute("phanQuyenChucNang");
		this.setError("");
		return "okPQCN";
	}

	public String getNhom() {
		return nhom;
	}
	

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setNhom(String groudFuction) {
		this.nhom = groudFuction;
	}

	public String getIdThanhVien() {
		return idThanhVien;
	}

	public void setIdThanhVien(String idThanhVien) {
		this.idThanhVien = idThanhVien;
	}

	public List<Table> getTables() {
		this.listTable();
		return tables;
	}

	public void setTables(List<Table> tables) {
		this.tables = tables;
	}

	public static void main(String[] args) {
		PhanQuyenChucNang pq = new PhanQuyenChucNang();
		pq.setNhom("2");
//		pq.setUserName("kimhong");
		System.out.println(pq.save());
	}
}
